<template>
    <div class="w-full h-full bg-white p-3">
        <Bar>
            <span class="bar-span">到期会员 ({{tableData.length}})</span>
        </Bar>
        <el-table :data="tableData" border style="width: 100%" show-overflow-tooltip>
            <el-table-column prop="name" label="客户姓名" />
            <el-table-column prop="phone" label="联系电话" />
            <el-table-column prop="address" label="客户地址" />
            <el-table-column prop="shopName" label="所属分店">
                <template #default="{ row }">
                    <assign-shop
                        v-model:shopName="row.shopName"
                        :memberId="row.index"
                        type="contract"
                    />
                </template>
            </el-table-column>
            <el-table-column prop="type" label="客户类型"/>
            <el-table-column prop="contact_time" label="创建时间">
                <template #default="scope">
                    {{ formatDate(scope.row.contact_time) }}
                </template>
            </el-table-column>
            <el-table-column prop="due_time" label="到期时间">
                <template #default="scope">
                    {{ formatDate(scope.row.due_time) }}
                </template>
            </el-table-column>
            <el-table-column prop="expirationDays" label="过期天数" class-name="fontColor">
                <template #default="scope">
                    {{ scope.row.expirationDays > 0 ? scope.row.expirationDays : '' }}
                </template>
            </el-table-column>
            <el-table-column label="操作" >
              <template #default="scope">
                <el-button type="success" @click="handleRenew(scope.row)">续约</el-button>
              </template>
            </el-table-column>
        </el-table>

        <!-- 续约对话框 -->
        <el-dialog
            v-model="renewDialogVisible"
            title="合同续约"
            width="30%"
        >
            <el-form :model="renewForm" label-width="100px">
                <el-form-item label="续约天数">
                    <el-input-number v-model="renewForm.renewDays" :min="1" :max="365" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="renewDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitRenew">确认</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 分配店铺对话框 -->
        <el-dialog
            v-model="shopDialogVisible"
            title="分配店铺"
            width="30%"
        >
            <el-select v-model="selectedShopId" placeholder="请选择店铺" style="width: 100%">
                <el-option
                    v-for="item in shopList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="shopDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmAssignShop">
                        确认
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="remind">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import Bar from '@/components/Bar.vue'
import request from '@/api'
import { useStaffStore } from '@/stores/useStaffStore'
import AssignShop from '@/components/AssignShop.vue'

interface Contract {
  index: number
  name: string
  phone: string
  address: string
  shop: number
  shopName: string
  type: string
  contact_time: string
  due_time: string
  tags: string[] | null
  expirationDays: number
}

const tableData = ref<Contract[]>([])

const staffStore = useStaffStore()
const shopDialogVisible = ref(false)
const currentRow = ref<Contract | null>(null)
const selectedShopId = ref<number>()

// 获取店铺列表
const shopList = computed(() => {
    return staffStore.shopList.map((shop: { id: number; shop_name: string }) => ({
        value: shop.id,
        label: shop.shop_name
    }))
})

// 格式化日期
const formatDate = (dateStr: string) => {
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 获取即将到期的合同列表
const getExpiringContracts = async () => {
  try {
    const response = await request({
      url: '/api/contract/expiring',
      method: 'get'
    })
    // 格式化日期并计算实时过期天数，只保留过期天数大于0的记录
    tableData.value = response.data
      .map((item: Contract) => {
        const expireDate = new Date(item.due_time)
        const currentDate = new Date()
        const daysDiff = Math.floor((currentDate.getTime() - expireDate.getTime()) / (24 * 60 * 60 * 1000))
        
        return {
          ...item,
          expirationDays: daysDiff
        }
      })
      .filter((item: Contract) => item.expirationDays > 0)
  } catch (error) {
    ElMessage.error('获取合同列表失败')
  }
}

// 定时更新过期天数
const updateExpirationDays = () => {
  if (tableData.value.length > 0) {
    tableData.value = tableData.value
      .map(item => {
        const expireDate = new Date(item.due_time)
        const currentDate = new Date()
        const daysDiff = Math.floor((currentDate.getTime() - expireDate.getTime()) / (24 * 60 * 60 * 1000))
        
        return {
          ...item,
          expirationDays: daysDiff
        }
      })
      .filter((item: Contract) => item.expirationDays > 0)
  }
}

// 续约相关
const renewDialogVisible = ref(false)
const renewForm = ref({
  id: 0,
  renewDays: 1,
})

// 续约合同
const renewContract = async (id: number, renewDays: number) => {
  return request({
    url: '/api/contract/renew',
    method: 'post',
    data: {
      id,
      renewDays
    }
  })
}

// 打开续约对话框
const handleRenew = (row: Contract) => {
  renewForm.value.id = row.index
  renewForm.value.renewDays = 1
  renewDialogVisible.value = true
}

// 提交续约
const submitRenew = async () => {
  try {
    // 找到当前续约的合同在表格中的索引
    const index = tableData.value.findIndex(item => item.index === renewForm.value.id)
    if (index !== -1) {
      const contract = tableData.value[index]
      // 计算新的到期时间
      const currentDate = new Date()
      const expireDate = new Date(contract.due_time)
      const newExpireDate = new Date(expireDate.getTime() + renewForm.value.renewDays * 24 * 60 * 60 * 1000)
      
      // 计算更新后的过期天数
      const daysDiff = Math.floor((currentDate.getTime() - newExpireDate.getTime()) / (24 * 60 * 60 * 1000))
      
      await renewContract(renewForm.value.id, renewForm.value.renewDays)
      ElMessage.success('续约成功')
      
      // 如果更新后不再过期，从表格中移除该条记录
      if (daysDiff <= 0) {
        tableData.value.splice(index, 1)
      } else {
        // 如果仍然过期，更新记录
        tableData.value[index] = {
          ...contract,
          due_time: newExpireDate.toISOString(),
          expirationDays: daysDiff
        }
      }
      
      renewDialogVisible.value = false
    }
  } catch (error) {
    ElMessage.error('续约失败')
  }
}

// 处理分配店铺
const handleAssignShop = (row: Contract) => {
    currentRow.value = row
    selectedShopId.value = undefined
    shopDialogVisible.value = true
}

// 确认分配店铺
const confirmAssignShop = async () => {
    if (!selectedShopId.value || !currentRow.value) {
        ElMessage.warning('请选择店铺')
        return
    }
    try {
        const resp = await request({
            url: '/api/member/assignShop',
            method: 'put',
            params: {
                memberId: currentRow.value.index,
                shopId: selectedShopId.value
            }
        })
        if (resp.status === 200) {
            ElMessage.success('分配店铺成功')
            // 更新当前行的店铺信息
            const shop = shopList.value.find((s: { value: number; label: string }) => s.value === selectedShopId.value)
            if (shop && currentRow.value) {
                currentRow.value.shopName = shop.label
            }
            shopDialogVisible.value = false
        }
    } catch (error) {
        console.error('分配店铺失败:', error)
        ElMessage.error('分配店铺失败')
    }
}

// 页面加载时获取数据并设置定时更新
onMounted(() => {
    getExpiringContracts()
    // 每小时更新一次过期天数
    const timer = setInterval(updateExpirationDays, 3600000)
    
    // 获取店铺列表
    if (staffStore.shopList.length === 0) {
        staffStore.fetchShopList()
    }
    
    // 组件卸载时清除定时器
    onUnmounted(() => {
        clearInterval(timer)
    })
})
</script>

<style scoped>
.el-table :deep(.cell) {
  text-align: center;
}
:deep(.fontColor .cell){
  color: red;
}
:deep(.is-leaf .cell){
  color: var(--el-table-header-text-color);
}
</style>